package be.aquafin.ws.rest;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;

import be.aquafin.klipdf.model.Objecttype;
import be.aquafin.klipdf.model.SpatialObject;
import be.aquafin.klipdf.service.DataService;
import be.aquafin.klipdf.service.SpatialService;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

/**
 * @author user2080
 * 
 *         Spatial to non-spatial converter
 * 
 */
@Path("/")
@ComponentScan
public class SpatialEndPoint {
	private static final Logger logger = LoggerFactory.getLogger(SpatialEndPoint.class);
	private SpatialService spatialService;
	
	private DataService dataService;
	private WKTReader reader = new WKTReader();

	@GET
	@Path("get")
	@Produces(MediaType.TEXT_PLAIN)
	public String getData(@QueryParam(value = "geometry") String geometryWKT, @QueryParam(value = "objecttype") String objecttypeStr) {
		if (StringUtils.isEmpty(geometryWKT)) {
			return "[geometry] cannot be empty";
		}
		if (StringUtils.isEmpty(objecttypeStr)) {
			return "[objecttype] cannot be empty";
		}
		Geometry geometry = null;
		try {
			geometry = reader.read(geometryWKT).buffer(5.0);
		} catch (ParseException ex) {
			logger.error("unable to parse geometry. Must be WKT.");
			return "ERROR - unable to parse geometry. Must be WKT.";
		}
		Objecttype objecttype = Objecttype.valueOf(objecttypeStr.toUpperCase());
		List<? extends SpatialObject> spatialObjects = spatialService.getSpatialData(objecttype, geometry);
		String dataResults = dataService.getData(objecttype, spatialObjects);
		return dataResults;
	}

	public void setSpatialService(SpatialService spatialService) {
		this.spatialService = spatialService;
	}
	
	@Autowired
	public void setDataService(DataService dataService) {
		this.dataService = dataService;
	}

}
